package com.jsh.erp.service.dailyItem;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.DailyHeadMapper;
import com.jsh.erp.datasource.mappers.DailyItemMapper;
import com.jsh.erp.datasource.mappers.DailyItemMapperEx;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.dailyHead.DailyHeadService;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class DailyItemService {
    private Logger logger = LoggerFactory.getLogger(DailyItemService.class);

    @Resource
    private DailyItemMapper dailyItemMapper;

    @Resource
    private DailyItemMapperEx dailyItemMapperEx;
    @Resource
    private LogService logService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private DailyHeadService dailyHeadService;
    @Resource
    private DailyHeadMapper dailyHeadMapper;

    public DailyItem getDailyItem(String id)throws Exception {
        DailyItem result=null;
        try{
            result=dailyItemMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<DailyItem> getDailyItemListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<DailyItem> list = new ArrayList<>();
        try{
            DailyItemExample example = new DailyItemExample();
            example.createCriteria().andIdIn(idList);
            list = dailyItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DailyItem> getDailyItem()throws Exception {
        DailyItemExample example = new DailyItemExample();
        example.createCriteria().andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DailyItem> list=null;
        try{
            list=dailyItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<DailyItem> select(String name, int offset, int rows)throws Exception {
        List<DailyItem> list=null;
        try{
            list=dailyItemMapperEx.selectByConditionDailyItem(name, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countDailyItem(String name)throws Exception {
        Long result=null;
        try{
            result=dailyItemMapperEx.countsByDailyItem(name);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertDailyItem(JSONObject obj, HttpServletRequest request)throws Exception {
        DailyItem dailyItem = JSONObject.parseObject(obj.toJSONString(), DailyItem.class);
        dailyItem.setUploadFlag("0");
        int result=0;
        try{
            result=dailyItemMapper.insertSelective(dailyItem);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateDailyItem(JSONObject obj, HttpServletRequest request)throws Exception {
        DailyItem dailyItem = JSONObject.parseObject(obj.toJSONString(), DailyItem.class);
        dailyItem.setUploadFlag("0");
        int result=0;
        try{
            result=dailyItemMapper.updateByPrimaryKeySelective(dailyItem);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteDailyItem(String id, HttpServletRequest request)throws Exception {
        return batchDeleteDailyItemByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDailyItem(String ids, HttpServletRequest request) throws Exception{
        return batchDeleteDailyItemByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteDailyItemByIds(String ids)throws Exception {
        int result =0;
        return result;
    }

    public int checkIsNameExist(String id, String name) throws Exception{
        DailyItemExample example = new DailyItemExample();
        example.createCriteria().andIdNotEqualTo(id).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<DailyItem> list =null;
        try{
            list=dailyItemMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }

    public List<DailyItem> getListByHeaderId(String headerId) throws Exception {
        List<DailyItem> list = null;
        try {
            DailyItemExample example = new DailyItemExample();
            example.createCriteria().andHeaderIdEqualTo(headerId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
            list = dailyItemMapper.selectByExample(example);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void deleteDailyItemHeadId(String headerId) throws Exception {
        try {
//            //1、查询删除前的单据明细
//            List<DailyItem> dailyItemList = getListByHeaderId(headerId);
            //2、删除单据明细
            dailyItemMapperEx.batchDeleteDailyItemByDailyHeadIds(new String[]{headerId});
//            //3、计算删除之后单据明细中商品的库存
//            for (DailyItem dailyItem : dailyItemList) {
//                updateCurrentStock(dailyItem);
//            }
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void saveDetials(String rows, String headerId, String actionType, HttpServletRequest request, boolean flag) throws Exception {
        //查询单据主表信息
//        DailyHead dailyHead = dailyHeadMapper.selectByPrimaryKey(headerId);
        //删除单据的明细
        deleteDailyItemHeadId(headerId);
        JSONArray rowArr = JSONArray.parseArray(rows);
        if (null != rowArr && rowArr.size() > 0) {
            for (int i = 0; i < rowArr.size(); i++) {
                DailyItem dailyItem = new DailyItem();
                JSONObject rowObj = JSONObject.parseObject(rowArr.getString(i));
                dailyItem.setHeaderId(headerId);

                if (StringUtil.isExist(rowObj.get("device"))) {
                    dailyItem.setDevice(rowObj.getString("device"));
                }
                if (StringUtil.isExist(rowObj.get("cashAmount"))) {
                    dailyItem.setCashAmount(rowObj.getBigDecimal("cashAmount"));
                }
                if (StringUtil.isExist(rowObj.get("bankAmount"))) {
                    dailyItem.setBankAmount(rowObj.getBigDecimal("bankAmount"));
                }
                if (StringUtil.isExist(rowObj.get("invoiceAmount"))) {
                    dailyItem.setInvoiceAmount(rowObj.getBigDecimal("invoiceAmount"));
                }
                if (StringUtil.isExist(rowObj.get("specialAmount"))) {
                    dailyItem.setSpecialAmount(rowObj.getBigDecimal("specialAmount"));
                }
                if (StringUtil.isExist(rowObj.get("giftAmount"))) {
                    dailyItem.setGiftAmount(rowObj.getBigDecimal("giftAmount"));
                }
                if (StringUtil.isExist(rowObj.get("discountAmount"))) {
                    dailyItem.setDiscountAmount(rowObj.getBigDecimal("discountAmount"));
                }
                if (StringUtil.isExist(rowObj.get("breakageAmount"))) {
                    dailyItem.setBreakageAmount(rowObj.getBigDecimal("breakageAmount"));
                }
                if (StringUtil.isExist(rowObj.get("subTotal"))) {
                    dailyItem.setSubTotal(rowObj.getBigDecimal("subTotal"));
                }
                if (StringUtil.isExist(rowObj.get("readingTotal"))) {
                    dailyItem.setReadingTotal(rowObj.getBigDecimal("readingTotal"));
                }
                if (StringUtil.isExist(rowObj.get("ttl"))) {
                    dailyItem.setTtl(rowObj.getBigDecimal("ttl"));
                }
                if (StringUtil.isExist(rowObj.get("boxAmount"))) {
                    dailyItem.setBoxAmount(rowObj.getBigDecimal("boxAmount"));
                }
                if (StringUtil.isExist(rowObj.get("deductAmount"))) {
                    dailyItem.setDeductAmount(rowObj.getBigDecimal("deductAmount"));
                }
                if (StringUtil.isExist(rowObj.get("difference"))) {
                    dailyItem.setDifference(rowObj.getBigDecimal("difference"));
                }
                if (StringUtil.isExist(rowObj.get("totalAmount"))) {
                    dailyItem.setTotalAmount(rowObj.getBigDecimal("totalAmount"));
                }
                if (StringUtil.isExist(rowObj.get("remark"))) {
                    dailyItem.setRemark(rowObj.getString("remark"));
                }
                if (StringUtil.isExist(rowObj.get("custom1"))) {
                    dailyItem.setCustom1(rowObj.getString("custom1"));
                }
                if (StringUtil.isExist(rowObj.get("custom2"))) {
                    dailyItem.setCustom2(rowObj.getString("custom2"));
                }
                if (StringUtil.isExist(rowObj.get("custom3"))) {
                    dailyItem.setCustom3(rowObj.getString("custom3"));
                }
                if (StringUtil.isExist(rowObj.get("custom4"))) {
                    dailyItem.setCustom4(rowObj.getString("custom4"));
                }
                if (StringUtil.isExist(rowObj.get("custom5"))) {
                    dailyItem.setCustom5(rowObj.getString("custom5"));
                }
                if (StringUtil.isExist(rowObj.get("custom6"))) {
                    dailyItem.setCustom6(rowObj.getBigDecimal("custom6"));
                }
                if (StringUtil.isExist(rowObj.get("custom7"))) {
                    dailyItem.setCustom7(rowObj.getBigDecimal("custom7"));
                }
                if (StringUtil.isExist(rowObj.get("custom8"))) {
                    dailyItem.setCustom8(rowObj.getBigDecimal("custom8"));
                }
                if (StringUtil.isExist(rowObj.get("custom9"))) {
                    dailyItem.setCustom9(rowObj.getBigDecimal("custom9"));
                }
                if (StringUtil.isExist(rowObj.get("custom10"))) {
                    dailyItem.setCustom10(rowObj.getBigDecimal("custom10"));
                }
                if (StringUtil.isExist(rowObj.get("custom11"))) {
                    dailyItem.setCustom11(rowObj.getInteger("custom11"));
                }
                if (StringUtil.isExist(rowObj.get("custom12"))) {
                    dailyItem.setCustom12(rowObj.getInteger("custom12"));
                }
                if (StringUtil.isExist(rowObj.get("custom13"))) {
                    dailyItem.setCustom13(rowObj.getInteger("custom13"));
                }
                if (StringUtil.isExist(rowObj.get("custom14"))) {
                    dailyItem.setCustom14(rowObj.getInteger("custom14"));
                }
                if (StringUtil.isExist(rowObj.get("custom15"))) {
                    dailyItem.setCustom15(rowObj.getInteger("custom15"));
                }
                this.insertDailyItemWithObj(dailyItem);
            }

        } else {
            throw new BusinessRunTimeException(ExceptionConstants.DEPOT_HEAD_ROW_FAILED_CODE,
                    String.format("zh".equals(systemConfigService.getLanCode()) ? ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG : ExceptionConstants.DEPOT_HEAD_ROW_FAILED_MSG_US));
        }
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertDailyItemWithObj(DailyItem dailyItem) throws Exception {
        try {
            dailyItem.setId(IdUtils.getUUID());
            dailyItem.setUploadFlag("0");
            dailyItemMapper.insertSelective(dailyItem);
        } catch (Exception e) {
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
    }

    public List<DailyItem> getDetailList(String headerId) throws Exception {
        List<DailyItem> list = null;
        try {
            list = dailyItemMapperEx.getDetailList(headerId);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
    public List<DailyItem> getDetailListByTime(String beginTime,String endTime) throws Exception {
        List<DailyItem> list = null;
        try {
            list = dailyItemMapperEx.getDetailListByTime(beginTime,endTime);
        } catch (Exception e) {
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }
}
